package com.java.basis.reference;

import java.lang.ref.SoftReference;

/**
 * @author wangning
 * @date 2023/5/18 15:28
 * 一些高速缓存会使用软引用
 * -Xms5m -Xmx5m -XX:+PrintGCDetails
 */
public class SoftReferenceDemo {
    public static void main(String[] args) {
//        softRef_Memory_Enough();
        softRef_Memory_NotEnough();//-Xms5m -Xmx5m -XX:+PrintGCDetails
    }

    //内存够用不回收，内存不够用回收
    //Enough：足够的
    public static void softRef_Memory_Enough() {
        Object o1 = new Object();
        SoftReference<Object> softReference = new SoftReference<>(o1);
        System.out.println(o1);
        System.out.println(softReference.get());
        o1 = null;
        System.gc();
        System.out.println(o1);
        System.out.println(softReference.get());

    }

    public static void softRef_Memory_NotEnough() {
        Object o1 = new Object();
        SoftReference<Object> softReference = new SoftReference<>(o1);
        System.out.println(o1);
        System.out.println(softReference.get());
        o1 = null;
        try {
            byte[] bytes = new byte[30 * 1024 * 1024];
        } catch (Throwable e) {
            e.printStackTrace();
        } finally {
            System.out.println("***" + o1);
            System.out.println("***" + softReference.get());

        }
    }
}
